<?php
namespace App\Logics;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\OrderStagesModel;
use App\Models\ChannelModel;
use App\Libs\Common\CsvUtil;

//逻辑处理
class OrderStagesLogic extends BaseLogic {


    public function __construct()
    {
        parent::__construct();

    }

    public function index(array $para)
    {
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;

        $order_status=isset($para['order_status'])?$para['order_status']:-1;
        $order_comefrom =isset($para['order_comefrom'])?$para['order_comefrom']:'';
        $order_id=isset($para['order_id'])?$para['order_id']:'';
        $goods_name=isset($para['goods_name'])?$para['goods_name']:'';
        $user_phone=isset($para['user_phone'])?$para['user_phone']:'';
        $user_name=isset($para['user_name'])?$para['user_name']:'';
        $start_time=isset($para['start_time'])?$para['start_time']:'';
        $end_time=isset($para['end_time'])?$para['end_time']:'';

        $where = $searchWhere = [];
        $whereRaw='';$whereCol=[];

        if($order_status && $order_status!=-1){
            $where['order_status'] = $order_status;
            $searchWhere[] = ['o.order_status',$order_status];
        }
        if($order_comefrom && $order_comefrom!=-1){
            $where['order_comefrom'] = $order_comefrom;
            $searchWhere[] = ['o.order_comefrom',$order_comefrom];
        }

        if ($order_id) {
            $where['order_id'] = $order_id;
            $searchWhere[] = ['o.order_id', 'like', $order_id . '%'];
        }

        if ($goods_name) {
            $where['goods_name'] = $goods_name;
            $searchWhere[] = ['o.goods_name', 'like', $goods_name . '%'];
        }
        if ($user_phone) {
            $where['user_phone'] = $user_phone;
            $searchWhere[] = ['o.user_phone', 'like', $user_phone . '%'];
        }
        if ($user_name) {
            $where['user_name'] = $user_name;
            $searchWhere[] = ['o.user_name', 'like', $user_name . '%'];
        }

        if ($start_time) {
            $where['start_time'] = $start_time;
            $whereRaw.="o.order_create_time > ? ";
            $whereCol[]=$start_time;
        }

        if ($end_time) {
            $where['end_time'] = $end_time;
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.="o.order_create_time <  ? ";
            $whereCol[]=$end_time;
        }

        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }



        $fields=['o.order_status','o.order_id','o.user_name','o.user_phone','o.order_comefrom','o.goods_name',
            'o.goods_price','o.order_tenancy_term','o.order_create_time',
            'order_stages.current_tenancy_term','order_stages.monthly_rent','order_stages.total_pay','order_stages.paid_monthly_rent','order_stages.repayment_time','order_stages.last_repayment_time',
            'order_stages.balance','order_stages.days_overdue','order_stages.amount_override','order_stages.order_goods_insurance','order_stages.goods_installation_charge','order_stages.cou_credit_amount',
            'order_stages.cou_onle_id','order_stages.fq_status','order_stages.alipay_fund_order_no','order_stages.order_stages_pay','order_stages.out_order_id','order_stages.create_time'
        ];
        $model=OrderStagesModel::join('orders as o','order_stages.order_id','=','o.order_id')
            ->where($searchWhere)->select($fields);
        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);



        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);

        $fq_status=config('sys.fq_status');
        $order_stages_pay=config('sys.order_stages_pay');
        $order_status=config('sys.order_status');
        foreach ($data['data'] as $k=>$v){
            $data['data'][$k]['order_status']=isset($order_status[$v['order_status']])?$order_status[$v['order_status']]:'';
            $data['data'][$k]['fq_status']=isset($fq_status[$v['fq_status']])?$fq_status[$v['fq_status']]:'';
            $data['data'][$k]['order_stages_pay']=isset($order_stages_pay[$v['order_stages_pay']])?$order_stages_pay[$v['order_stages_pay']]:'';
        }

        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        $excel_url="?";
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
            $excel_url.="&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        if(isset($where['per_page']))unset($where['per_page']);

        $channel=ChannelModel::pluck('cha_describe','cha_name');
        $channel=ob_to_array($channel);
        $arr=[
            'data'=>$data,
            'where'=>$where,
            'channel'=>$channel,
            'excel_url'=>$excel_url
        ];
        return $arr;
    }

    /** 还款订单
     * @param array $para
     * @return array
     */
    public function huanKuanOrders(array $para){
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $order_status=isset($para['order_status'])?$para['order_status']:-1;
        $order_comefrom =isset($para['order_comefrom'])?$para['order_comefrom']:'';
        $order_id=isset($para['order_id'])?$para['order_id']:'';
        $goods_name=isset($para['goods_name'])?$para['goods_name']:'';
        $user_phone=isset($para['user_phone'])?$para['user_phone']:'';
        $user_name=isset($para['user_name'])?$para['user_name']:'';
        $start_time=isset($para['start_time'])?$para['start_time']:'';
        $end_time=isset($para['end_time'])?$para['end_time']:'';
        $daochu=isset($para['daochu'])?$para['daochu']:0;

        $where = $searchWhere = [];
        $whereRaw='';$whereCol=[];

        if($order_status!=-1){
            $where['order_status'] = $order_status;
            $searchWhere[] = ['o.order_status',$order_status];
        }
        if($order_comefrom && $order_comefrom!=-1){
            $where['order_comefrom'] = $order_comefrom;
            $searchWhere[] = ['o.order_comefrom',$order_comefrom];
        }

        if ($order_id) {
            $where['order_id'] = $order_id;
            $searchWhere[] = ['o.order_id', 'like', $order_id . '%'];
        }

        if ($goods_name) {
            $where['goods_name'] = $goods_name;
            $searchWhere[] = ['o.goods_name', 'like', $goods_name . '%'];
        }
        if ($user_phone) {
            $where['user_phone'] = $user_phone;
            $searchWhere[] = ['o.user_phone', 'like', $user_phone . '%'];
        }
        if ($user_name) {
            $where['user_name'] = $user_name;
            $searchWhere[] = ['o.user_name', 'like', $user_name . '%'];
        }

        if ($start_time) {
            $where['start_time'] = $start_time;
            $whereRaw.="o.order_create_time > ? ";
            $whereCol[]=$start_time;
        }

        if ($end_time) {
            $where['end_time'] = $end_time;
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.="o.order_create_time <  ? ";
            $whereCol[]=$end_time;
        }

        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }
        $channel=ChannelModel::pluck('cha_describe','cha_name');
        $channel=ob_to_array($channel);

        $fieldsRaw="sum(order_stages.days_overdue) as count_days_overdue, sum(order_stages.cou_credit_amount) as cou_credit_amount, 
        o.order_status,o.order_id,o.user_name,o.user_phone,o.order_comefrom,o.goods_name,o.goods_price,o.order_create_time,o.order_tenancy_term,
        o.order_repay_period,o.order_rema_amount_pay,o.order_amount_actually_paid,o.order_amount_override,o.order_installation_charge,o.order_goods_insurance";

        $model=OrderStagesModel::join('orders as o','order_stages.order_id','=','o.order_id')
            ->whereIn('o.order_status',[4,5,8])->where($searchWhere)->selectRaw($fieldsRaw)->groupBy("o.order_id");
        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);

        $order_status=config('sys.order_status');
        if($daochu==1){
            $data=$model->limit(100)->get();
            $data=ob_to_array($data);
            foreach ($data as $k=>$v){
                $data[$k]['order_status']=isset($order_status[$v['order_status']])?$order_status[$v['order_status']]:'';
                $data[$k]['order_comefrom']=isset($channel[$v['order_comefrom']])?$channel[$v['order_comefrom']]:'';
            }




            $csv = new CsvUtil();
            $filename = '还款列表' . date('YmdHis') . '.csv';
            // 输出Excel文件头
            $csv->csvHeader($filename);
            $head = ['订单状态','订单号','客户姓名','客户手机号','订单来源','商品名称','商品价格','下单时间','总期数','剩余还款期数','剩余还款金额','实付金额','逾期金额', '逾期总天数','优惠金额','安装包金额','意外保障费'];
            $csv->outputData($head);

            $limit = 100000;     //刷新缓存限制，避免php缓存过大
            $cnt   = 0;         //用于计算缓存数量
            $size  = 20000;
            foreach($data as $item){
                $_data=[
                    $item['order_status'],
                    "\t".$item['order_id'],
                    $item['user_name'],
                    "\t".$item['user_phone'],
                    $item['order_comefrom'],
                    $item['goods_name'],
                    $item['goods_price'],
                    $item['order_create_time'],
                    $item['order_tenancy_term'],
                    $item['order_repay_period'],
                    $item['order_rema_amount_pay'],
                    $item['order_amount_actually_paid'],
                    $item['order_amount_override'],
                    $item['count_days_overdue'],
                    $item['cou_credit_amount'],
                    $item['order_installation_charge'],
                    $item['order_goods_insurance'],
                ];

                $cnt++;
                if ($limit == $cnt)
                {
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    $csv->csvFlush($cnt);
                }
                $csv->outputData($_data);
            }
            $csv->closeFile();  //每生成一个文件关闭
            exit;
        }

        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);
        foreach ($data['data'] as $k=>$v){
            $data['data'][$k]['order_status']=isset($order_status[$v['order_status']])?$order_status[$v['order_status']]:'';
            $data['data'][$k]['order_comefrom']=isset($channel[$v['order_comefrom']])?$channel[$v['order_comefrom']]:'';
        }

        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        $excel_url="?";
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
            $excel_url.="&$k=$v";
        }
        $data['page_url'] = trim($url, '&');
        if(isset($where['per_page']))unset($where['per_page']);


        $arr=[
            'data'=>$data,
            'where'=>$where,
            'channel'=>$channel,
            'excel_url'=>$excel_url
        ];
        return $arr;
    }

    public function orderStagesExcel(array $para){
        $order_status=isset($para['order_status'])?$para['order_status']:-1;
        $order_comefrom =isset($para['order_comefrom'])?$para['order_comefrom']:'';
        $order_id=isset($para['order_id'])?$para['order_id']:'';
        $goods_name=isset($para['goods_name'])?$para['goods_name']:'';
        $user_phone=isset($para['user_phone'])?$para['user_phone']:'';
        $user_name=isset($para['user_name'])?$para['user_name']:'';
        $start_time=isset($para['start_time'])?$para['start_time']:'';
        $end_time=isset($para['end_time'])?$para['end_time']:'';

        $searchWhere = [];
        $whereRaw='';$whereCol=[];

        if($order_status && $order_status!=-1){
            $where['order_status'] = $order_status;
            $searchWhere[] = ['o.order_status',$order_status];
        }

        if($order_comefrom && $order_comefrom!=-1){
            $searchWhere[] = ['o.order_comefrom',$order_comefrom];
        }

        if ($order_id) {
            $searchWhere[] = ['o.order_id', 'like', $order_id . '%'];
        }

        if ($goods_name) {
            $searchWhere[] = ['o.goods_name', 'like', $goods_name . '%'];
        }
        if ($user_phone) {
            $searchWhere[] = ['o.user_phone', 'like', $user_phone . '%'];
        }
        if ($user_name) {
            $searchWhere[] = ['o.user_name', 'like', $user_name . '%'];
        }

        if ($start_time) {
            $whereRaw.="o.order_create_time > ? ";
            $whereCol[]=$start_time;
        }

        if ($end_time) {
            if($whereRaw)$whereRaw.=" and ";
            $whereRaw.="o.order_create_time <  ? ";
            $whereCol[]=$end_time;
        }



        $fields=['o.order_status','o.order_id','o.user_name','o.user_phone','o.order_comefrom','o.goods_name','o.order_amount_actually_paid',
            'o.goods_price','o.order_tenancy_term','o.order_create_time',
            'order_stages.current_tenancy_term','order_stages.monthly_rent','order_stages.total_pay','order_stages.paid_monthly_rent','order_stages.repayment_time','order_stages.last_repayment_time',
            'order_stages.balance','order_stages.days_overdue','order_stages.amount_override','order_stages.order_goods_insurance','order_stages.goods_installation_charge','order_stages.cou_credit_amount',
            'order_stages.cou_onle_id','order_stages.fq_status','order_stages.alipay_fund_order_no','order_stages.order_stages_pay','order_stages.out_order_id','order_stages.create_time'
        ];
        $model=OrderStagesModel::join('orders as o','order_stages.order_id','=','o.order_id')
            ->select($fields)->where($searchWhere);
        if($whereRaw)$model->whereRaw($whereRaw,$whereCol);
        $data=$model->limit(100)->get();
        $data=ob_to_array($data);

        $channels=ChannelModel::pluck('cha_describe','cha_name');
        $channels=ob_to_array($channels);
        $fq_status=config('sys.fq_status');
        $order_status=config('sys.order_status');
        foreach($data as $k=>$v){
            $data[$k]['cha_describe']=isset($channels[$v['order_comefrom']])?$channels[$v['order_comefrom']]:'';
            $data[$k]['fq_status']=isset($fq_status[$v['fq_status']])?$fq_status[$v['fq_status']]:'';
            $data[$k]['order_status']=isset($order_status[$v['order_status']])?$order_status[$v['order_status']]:'';
        }
        set_time_limit(0); //设置请求时间
        $filename = '还款列表' . date('YmdHis') . '.csv';


        $csv=new CsvUtil();
        $csv->csvHeader($filename);
        $head = ['订单状态','订单号','客户姓名','客户手机号','订单来源','商品名称','商品价格','下单时间','总期数',
            '当前期数','分期状态','月租金','意外保障费','安装包金额','优惠券减免金额','实际应付租金','还款时间','最好还款时间',
            '已还金额','逾期金额','逾期天数'
        ];

        $csv->outputData($head);
        $limit = 100000;     //刷新缓存限制，避免php缓存过大
        $cnt   = 0;         //用于计算缓存数量
        $size  = 20000;

        foreach($data as $item)
        {
            $_data=[
                $item['order_status'],
                "\t".$item['order_id'],
                $item['user_name'],
                "\t".$item['user_phone'],
                $item['cha_describe'],
                $item['goods_name'],
                $item['goods_price'],
                $item['order_create_time'],
                $item['order_tenancy_term'],
                $item['current_tenancy_term'],
                $item['fq_status'],
                $item['monthly_rent'],
                $item['order_goods_insurance'],
                $item['goods_installation_charge'],
                $item['cou_credit_amount'],
                $item['total_pay'],
                $item['repayment_time'],
                $item['last_repayment_time'],
                $item['paid_monthly_rent'],
                $item['amount_override'],
                $item['days_overdue'],
            ];

            $cnt++;

            if ($limit == $cnt)
            {
                //刷新一下输出buffer，防止由于数据过多造成问题
                $csv->csvFlush($cnt);
            }
            $csv->outputData($_data);
        }
        $csv->closeFile();  //每生成一个文件关闭
        exit;

    }

    //通过订单id获取分期表数据
    public static function getListByOrderId($order_id){
      $data= OrderStagesModel::where('order_id',$order_id)->orderBy("current_tenancy_term", "asc")->get()->toArray();

      return $data;
    }

    /** 通过订单id获取分期
     * @param int $order_id
     * @return mixed
     */
    public function getOrderStagesListByOrderId(string $order_id){
        $data=OrderStagesModel::where('order_id',$order_id)->get();
        $data= ob_to_array($data);
        $fq_status=config('sys.fq_status');
        foreach ($data as $k=>$v){
            $data[$k]['fq_status']=$fq_status[$v['fq_status']]??'';
        }
        return $data;
    }










}
